<?php

/**
 * 73YC 评论页面
 * ============================================================================
 * * 版权所有 20013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2013-10-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
/* 载入语言文件 */
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');
include('region_select.php');
$user_id = $_SESSION['user_id'];
$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'default';
$order_id  = isset($_REQUEST['order_id']) ? trim($_REQUEST['order_id']) : '';
$affiliate = unserialize($GLOBALS['_CFG']['affiliate']);
$smarty->assign('affiliate', $affiliate);
$back_act='';

// 不需要登录的操作或自己验证是否登录（如ajax处理）的act
$not_login_arr =array('comment_process','comment_false','login','act_login','register','act_register','act_edit_password','get_password','send_pwd_email','password', 'signin', 'add_tag', 'collect', 'return_to_cart', 'logout', 'email_list', 'validate_email', 'send_hash_mail', 'order_query', 'is_registered', 'check_email','clear_history','qpassword_name', 'get_passwd_question', 'check_answer');
/* 显示页面的action列表 */
$ui_arr = array( 'comment', 'join_list','join_detail','register', 'login', 'profile', 'profile_pass', 'order_list', 'order_detail', 'address_list', 'collection_list',
'message_list', 'tag_list', 'get_password', 'reset_password', 'booking_list', 'add_booking', 'account_raply','message',
'account_deposit', 'account_log', 'account_detail', 'act_account', 'pay', 'default', 'bonus', 'group_buy', 'group_buy_detail', 'affiliate', 'comment_list','validate_email','track_packages', 'transform_points','qpassword_name', 'get_passwd_question', 'check_answer' ,'void_join');

/* 未登录处理 */
if (empty($_SESSION['user_id']))
{
    if (!in_array($action, $not_login_arr))
    {
        if (in_array($action, $ui_arr))
        {
            if (!empty($_SERVER['QUERY_STRING']))
            {
                $back_act = 'user.php?' . strip_tags($_SERVER['QUERY_STRING']);
            }
            $action = 'login';
        }
        else
        {
            //未登录提交数据。非正常途径提交数据！
            die($_LANG['require_login']);
        }
    }
}

/* 如果是显示页面，对页面进行相应赋值 */
if (in_array($action, $ui_arr))
{
    assign_template();
    $position = assign_ur_here(0, $_LANG['user_center']);
    $smarty->assign('page_title', $position['title']); // 页面标题
    $smarty->assign('ur_here',    $position['ur_here']);
    $sql = "SELECT value FROM " . $ecs->table('shop_config') . " WHERE id = 419";
    $row = $db->getRow($sql);
    $car_off = $row['value'];
    $smarty->assign('car_off',       $car_off);
    /* 是否显示积分兑换 */
    if (!empty($_CFG['points_rule']) && unserialize($_CFG['points_rule']))
    {
        $smarty->assign('show_transform_points',     1);
    }
    $smarty->assign('helps',      get_shop_help());        // 网店帮助
    $smarty->assign('data_dir',   DATA_DIR);   // 数据目录
    $smarty->assign('action',     $action);
    $smarty->assign('lang',       $_LANG);
    include_once(ROOT_PATH .'includes/lib_clips.php');
    $smarty->assign('info',        get_user_default($user_id));


}

if($action=="comment"){
    include_once(ROOT_PATH . 'includes/lib_order.php');    
    if(empty($order_id)){ header("location:index.php");}
    $orders=order_goods($order_id);
    foreach ($orders as $key => $value) {
        $orders["goods"][$value["goods_id"]]=$value;
    }
    $orders_goods=array_values($orders["goods"]);
    $Sales=get_goods_rank($orders_goods["0"]["goods_id"]);
    $smarty->assign('sales',$Sales);
    $rank=    count_rank($orders_goods["0"]["goods_id"]);
    $rank=$rank?$rank*20:100;
    $orders_goods[0]['give_integral'] = $orders_goods[0]['give_integral']>0?$orders_goods[0]['give_integral']:floor($orders_goods[0]['goods_price']);
    $orders_goods[0]['give_growth'] = $orders_goods[0]['give_integral']; //成长值
    if($orders_goods[0]['market_price'] == 0){//不存在市场价时的市场价
        $orders_goods[0]['market_price'] = sprintf('%.2f',($orders_goods[0]['goods_price'])*1.2);
    }
    $smarty->assign('rank',$rank);
    $smarty->assign('goods',$orders_goods);
    $smarty->assign('order_id',$order_id);
    $smarty->assign('id', $orders_goods["0"]["goods_id"]);
    $smarty->assign('type',         0);
    $smarty->assign('goodrate', rate($orders_goods["0"]["goods_id"]));//添加好评率
    $smarty->assign('display' , 1);                  //作为是否显示好评率的标志，与商品详细页
    // 查询订单是否已经评论
    $sql = "SELECT comment FROM ".$GLOBALS['ecs']->table('order_info')." WHERE `order_id` =".$order_id." AND  `user_id` =".$_SESSION['user_id']." AND `order_status` ='5' AND `shipping_status` ='2' AND `pay_status` ='2'";
    $comment= $db->getRow($sql);
    if(!isset($comment)||empty($comment)){
        header("location:user.php");
    }
    $comment=$comment["comment"];
    if(!isset($comment)||$comment=="2"){
        header("location:user.php");
    }
    elseif ($comment=='1') {
        $smarty->display('comment_more.dwt');
    }
    else{
        $smarty->display('comment.dwt'); 
    }
 
}
elseif ($action == 'login')
{
    if (empty($back_act))
    {
        if (empty($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
        {
            $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
        }
        else
        {
            $back_act = 'user.php';
        }

    }
    $captcha = intval($_CFG['captcha']);
    if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0)
    {
        $GLOBALS['smarty']->assign('enabled_captcha', 1);
        $GLOBALS['smarty']->assign('rand', mt_rand());
    }

    $smarty->assign('back_act', $back_act);
    $smarty->display('login.dwt');
}

//评论成功页面
elseif ($action=='comment_success'){
    require(ROOT_PATH . 'includes/lib_transaction.php');
    $info = get_user_head_rank();

    // 查询订单是否已经评论
    $sql = "SELECT order_id, COUNT(*) AS order_count FROM ".$GLOBALS['ecs']->table('order_info')." WHERE `user_id` =".$_SESSION['user_id']." AND `order_status` ='5' AND `shipping_status` ='2' AND `pay_status` ='2' AND `comment`='0'";
    $row= $db->getRow($sql);
    $order = array();
    if(!isset($row)||empty($row)||$row['order_count']==0){
        $order['count'] = 0;
        $order['growth'] = 0;
        $order['href']  = 'javascript:void(0)'; 
    }else{
        $order['count'] = $row['order_count'];
        $order['growth'] = 2*$order['count'];
        $order['href']  = '/comments.php?act=comment&order_id=' . $row['order_id'];
    }
    $smarty->assign('order', $order);
    $smarty->assign('info', $info);
    $smarty->display('comment_success.dwt');
}
//处理对评论的评价
elseif ($action=='comment_good_bad'){
    require(ROOT_PATH . 'includes/cls_json.php');
    $_POST['comment']=strip_tags(urldecode($_POST['comment']));
    $_POST['comment']= json_str_iconv($_POST['comment']);
    $result = array('error' => 0, 'message' => '', 'count' => '', 'nodename'=>'');
    $json  = new JSON;

   if (empty($_POST['comment']))
    {
        $result['error'] = 1;
        $result['message'] = '网络错误！'; 
        die($json->encode($result));
    }
    $comment = $json->decode($_POST['comment']);//将对象编译成字符串
    //检查是否已对评论评价
    $sql = "SELECT comment_id FROM ".$GLOBALS['ecs']->table('comment_gob')." WHERE comment_id=".$comment->comment_id." AND user_id=".$_SESSION['user_id'];
    $res= $db->getRow($sql);
    if(isset($res) && !empty($res)){
        //评论已被当前用户评价
        $result['error'] = 1;
        $result['message'] = '您已对该评论进行评价！';  
    }else{
        //插入数据
        $sql = 'INSERT INTO ' . $GLOBALS['ecs']->table('comment_gob') . '(comment_id, user_id, good_bad) VALUES (' . 
            $comment->comment_id . ',' . $_SESSION['user_id'] . ',' . $comment->choice . ')';
        $db->query($sql);

        //获得评论评价数目 (最新)
        $sql = 'SELECT COUNT(*) FROM ' . $GLOBALS['ecs']->table('comment_gob') . ' WHERE good_bad=' . $comment->choice . ' AND comment_id=' . $comment->comment_id;
        $result['count'] = $db->getOne($sql);

        //拼接DOM节点名
        $result['nodename'] = ($comment->choice==1) ? 'good_' . $comment->comment_id : 'bad_' . $comment->comment_id;
    }
    die($json->encode($result));
}

//虚假评论页面
elseif($action=='comment_false' && ($_SESSION['user_id'] == '1549' OR $_SESSION['user_id'] == '1')){
    $goods_id=!empty($_REQUEST['goods_id'])?$_REQUEST['goods_id']:'';
    if($goods_id){
       $goods=get_goods_info($goods_id);
       $smarty->assign('goods', $goods);
    }
    $smarty->display('comment_false.dwt');
}
//处理虚假评论
elseif ($action=='comment_process') {
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $_REQUEST['cmt'] = isset($_REQUEST['cmt']) ? json_str_iconv($_REQUEST['cmt']) : '';
    $data=$json->decode($_REQUEST['cmt']);
    $goods_id=$data->goods_id;//评论商品ID
    $goods_comment=$data->goods_comment;//商品评论内容
    $username = $data->username;//购买者
    $add_time = $data->post_date?strtotime($data->post_date . ' 00:00:00'):time();//购买者
    $gc = explode('//',$data->goods_comment);
    $gu = explode('//',$data->username);
    $sql = "INSERT INTO " .$GLOBALS['ecs']->table('comment') .
               "( goods_id,user_name, content,comment_rank, add_time) VALUES " ;
    foreach ($gu as $key => $value) {
        if($gc[$key]){
            if($key != 0) $sql .= ",";
            $sql .= "('".$goods_id."','".$value."', '".$gc[$key]."', '5', '".$add_time."')";
        }
    }
    // 插入评论
    $result = $GLOBALS['db']->query($sql);
    zuojiajilu($goods_id, count($gu), ($add_time-432000), ($add_time-259200), $gu, 1, 2);
    if($result){
        $massage='添加评论成功';
        echo $json->encode($massage);
    }
}
// 月销量
function get_goods_rank($goods_id)
{
    /* 查询该商品销量 */
    $sql = 'SELECT IFNULL(SUM(g.goods_number), 0) ' .
        'FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o, ' .
            $GLOBALS['ecs']->table('order_goods') . ' AS g ' .
        "WHERE o.order_id = g.order_id " ." AND g.goods_id = '$goods_id'";
    $sales_count = $GLOBALS['db']->getOne($sql);
    return $sales_count;
}
//商品评分
function count_rank($goods_id){
    $sql = 'SELECT comment_rank FROM ' . $GLOBALS['ecs']->table('comment') . "WHERE goods_id='".$goods_id."'";
    $sales_count = $GLOBALS['db']->getall($sql);
    foreach ($sales_count as $key => $value) {
        $count=$count+$value["comment_rank"];
    }
    $sales_count=ceil($count/count($sales_count));
    return $sales_count;
}

// 好评率
function rate($goods_id)
{
    $count = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('comment') . " AS c " . 
            " WHERE c.goods_id ='" . $goods_id . "'" ); 

    $sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('comment') . " AS c " . 
        " WHERE c.goods_id ='" . $goods_id . "' AND ";
    $good   = $GLOBALS['db']->getOne($sql . 'comment_rank = 5');
    $goodrate   = '';
    if($count != 0){
        $goodrate = ($good == 0) ? 0 : sprintf('%.3f', $good/$count)*100;
    }else{
        $goodrate = 0;
    }
    return $goodrate;
}

/* 做假记录函数
* $goods_id   商品ID
* $count      要加的记录总数
* $start_time 记录范围开始时间
* $end_time   记录范围结束时间
* $user_name_arr  用户名随机数据
* $goods_number_one  记录购买商品数量最小值
* $goods_number_tow  记录购买商品数量最大值
*/
function zuojiajilu($goods_id = 0,$count = 0, $start_time = 0, $end_time = 0, $user_name_arr = array(), $goods_number_one = 1, $goods_number_two = 1){
    if(!$goods_id) return false;
    $sql ="SELECT g.goods_id,g.goods_name,ga.attr_value AS goods_attr,g.goods_sku FROM " . $GLOBALS['ecs']->table('goods') . " g LEFT JOIN " . $GLOBALS['ecs']->table('goods_attr') . " ga ON ga.goods_id = g.goods_id AND attr_id = 1 WHERE g.goods_id = $goods_id";
    $arr = $GLOBALS['db']->getAll($sql);
    $goods_name = $arr[0]['goods_name'];
    $sql = "INSERT INTO " . $GLOBALS['ecs']->table('order_goods') . '(order_id, goods_id, goods_name, goods_sku, product_id,goods_number,goods_attr,market_price,goods_price,send_number,is_real,parent_id,is_gift,goods_attr_id,user_name,add_time) VALUES ';
    for($i=0;$i<$count;$i++){
        $goods_attr = $arr[rand(0,count($arr)-1)]['goods_attr'];
        $user_name = $user_name_arr[$i];
        $add_time = rand($start_time,$end_time);
        $goods_number = rand($goods_number_one,$goods_number_two);
        if($i > 0) $sql .= ',';
        $sql .= "('0','$goods_id','$goods_name','0','0','$goods_number','$goods_attr','0.00','0.00','0','1','0','0','0','$user_name','$add_time')";
    }
    $GLOBALS['db']->query($sql);
}


?>